import config from '@/config/config';
import { ElNotification } from 'element-plus';
import useMenuStore from '@/stores/modules/menu';
const store = useMenuStore();
/**
 * @function request
 * @param {IParams} 参数
 * @return {Promise} 返回Promise对象
 * @description 封装uniapp的request
 * @author zhaoyongqiang
 *
 */

interface IHeader {
	'content-type'?: 'application/json' | 'application/x-www-form-urlencoded';
	token?: string;
	Authorization?: string;
}
interface IParams {
	url?: string;
	api: string;
	method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'HEAD' | 'OPTIONS' | 'TRACE';
	body?: any;
	query?: any;
	dataType?: 'json' | '';
	timeout?: number;
	responseType?: 'arraybuffer' | 'text';
	withCredentials?: true | false;
	auth?: true | false;
}
export default function request({
	url = config.baseUrl,
	api,
	method = 'GET',
	body,
	query,
	auth = true,
	dataType = 'json',
	timeout = 60000,
	responseType = 'text',
	withCredentials = false
}: IParams): Promise<any> {
	let header: IHeader = {
		'content-type': 'application/json'
	};
	if (query) {
		header = {
			'content-type': 'application/x-www-form-urlencoded'
		};
	}
	if (auth) {
		header = {
			...header,
			'Authorization': 'bearer '+uni.getStorageSync('loginInfo').token
		};
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: url + api,
			method,
			header,
			data: query || body,
			dataType,
			timeout,
			responseType,
			withCredentials,
			success: res => {
				if (res.statusCode === 200) {
					resolve(res.data);
				} else if (res.statusCode === 401) {
					ElNotification({
						title: '提示',
						type: 'error',
						message: '登录已过期，请重新登录'
					});
					// 登录过期
					uni.clearStorageSync();
					store.loginInfo = {
						buttons:[]
					};
					store.menuInfo = {
						defaultAct:'0',
						defaultOpen:[],
						pageTitle:'首页',
						isCollapse:false
					};
					uni.reLaunch({
						url: '/pages/login/login'
					});
				} else if (res.statusCode === 404) {
					ElNotification({
						title: '提示',
						type: 'error',
						message: '接口地址不存在'
					});
				} else if (res.statusCode >= 500) {
					ElNotification({
						title: '提示',
						type: 'error',
						message: '服务器错误'
					});
				}
			},
			fail: err => {
				// 请求失败 timeout 或者无网络等 域名错误等
				reject(err);
				ElNotification({
					title: '提示',
					type: 'error',
					message: '无法连接到服务器'
				});
			}
		});
	});
}
